<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
header('Content-Type:text/html;charset=utf-8');
class User extends MY_Controller 
{
    protected $code=null;
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('captcha');
        $this->load->helper('url');
        $this->load->model('user_model');
    }
    
    /*
    *登录页面
    */
    public function longin()
    {
        $login = site_url('user/user_login');
        $this->load->view('user/login', array('login'=>$login));
    }
    
     /*
    *注册页面
    */
    public function register()
    {
       
        $this->code();
        $cod = $this->code;
        $ajaxurl = site_url('user/ajaxurl');
        $formAction = site_url('user/register_add');//表单提交页面
        $this->load->view('user/register', array('formAction'=>$formAction,'ajaxurl'=>$ajaxurl, 'code'=>$cod));
    }
    
    /*
    *用户注册
    */
    public function register_add()
    {
        $username = $this->input->post('username');
        $email = $this->input->post('email');
        $userpwd = $this->input->post('userpwd');
        $result = $this->user_model->user_add($username, $email, $userpwd);
        if($result){
            
            redirect("user/longin", 'refresh');
        }
                
    }
    
    /*
    *用户登录验证
    */
    public function user_login()
    {
        $userinfo = $this->input->post('logintype');
        $userpwd = $this->input->post('pwd');
        $result = $this->user_model->login_check($userinfo, $userpwd);
        if(!$result)
        {
            echo "<script>
                    alert('用户信息有误');
                   window.history.go(-1);
                </script>";
                
        }else{
                redirect('welcome/index', 'refresh');
            }
        
    }
    
    /*
    *用户退出
    */
    public function user_logout()
    {
       
        setcookie(session_name(),'',time()-3600,'/');

        $_SESSION=array();

        session_destroy();

        redirect('welcome/index', 'refresh');
    }
    
    /*
    *ajax请求方法
    */
    public function ajaxurl()
    {
       $val = $this->input->post('val');
       $resu = $this->user_model->register_ajax($val);
       if($resu){
            echo '1';
       }else{
            echo "2";
       }
    }
    
    /*
    *验证码
    */
    
    public function code(){
        $array=array('u'=>1,'b'=>2,'c','d','e','f','w','m'=>7,'v'=>6,'x'=>5,'f'=>4,'s'=>3);
        $strarr=array_rand($array, 4);
        $str = implode('', $strarr);
        
        $vals = array(
            'word'=>$str,
            'img_path' => './captcha/',
            'img_url' => base_url().'/captcha/',
            'expiration' => 3
            
            );

        $cap = create_captcha($vals);
        $this->code = $cap['image'];
        $_SESSION['code']=strtolower($str);
        
    }
}